import json
import socket

def handle_command(command):
    """处理客户端命令并返回响应结果"""
    if command.get('type') == 'ping':
        return {
            "status": "success",
            "result": "pong"
        }
    else:
        return {
            "status": "error",
            "result": f"Unknown command type: {command.get('type')}"
        }

def run_server():
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind(('localhost', 9876))
    server_socket.listen(1)
    print("Server is listening on port 9876...")

    try:
        while True:
            client_socket, addr = server_socket.accept()
            print(f"\nAccepted connection from {addr}")

            try:
                # 接收客户端数据
                data = client_socket.recv(65536)
                if not data:
                    print("Client sent empty data")
                    continue

                # 解析JSON命令
                try:
                    command = json.loads(data.decode('utf-8'))
                    print(f"Received command: {command}")

                    # 处理命令并发送响应
                    response = handle_command(command)
                    response_data = json.dumps(response).encode('utf-8')
                    client_socket.sendall(response_data)
                    print("Sent response:", response)

                except json.JSONDecodeError:
                    error_response = {
                        "status": "error",
                        "result": "Invalid JSON format"
                    }
                    client_socket.sendall(json.dumps(error_response).encode('utf-8'))
                    print("Sent JSON decode error response")

            except Exception as e:
                print(f"Error handling client: {e}")
            finally:
                client_socket.close()
                print("Client connection closed")

    except KeyboardInterrupt:
        print("\nServer shutting down...")
    finally:
        server_socket.close()

if __name__ == "__main__":
    run_server()
